local love = require 'love'
local fontHandler = require('assets-handler.font-handler')

local setColor = love.graphics.setColor
local drawg = love.graphics.draw
local drawRectangle = love.graphics.rectangle
local setLineWidth = love.graphics.setLineWidth
local line = love.graphics.line
local printg = love.graphics.print
local printf = love.graphics.printf

local height = Height
local width = Width
local padding = Padding

-- 长字符串输入（需控制换行，空行表示分段）
local longText = [[一、 游戏规则：

1. 出牌攻击对手,
    每回合出1到5张牌;

2. 凑出指定牌型, 
    大幅增加伤害;
   
3. 出手较大面值的牌, 
    会小幅增加伤害;

4. 对手生命值为 0 则获胜;
    牌库里的牌全出完则失败。

5. 出牌的牌中,
    未能用来凑牌型的牌, 
    被视为弃牌,
    但不算入弃牌数;

6. 每场匹配可以主动弃牌3次;

7. 出牌后会补充手牌至上限,
    手牌上限是8张;

8. 选择天赋可以获得特殊效果,
    如突破选牌上限等。

二、 得分规则：

1. 皇家同花顺
   → 2000 分 + 牌面分的伤害

2. 同花顺
   → 600 分 + 牌面分

3. 三带二
   → 175 分 + 牌面分

4. 同花
   → 125 分 + 牌面分

5. 顺子
   → 100 分 + 牌面分

6. 四条
   → 400 分 + 牌面分

7. 三条
   → 80 分 + 牌面分

8. 两对
   → 40 分 + 牌面分

9. 对子
   → 20 分 + 牌面分

10. 单高牌
    如果打出的卡牌没有组合, 
    不管是几张都算单高牌
    → 10 分 + 最高牌牌面分
    
11. 牌面分
    < 红桃 2 > → 2 分
    < 黑桃 3 > → 3 分
    ......
    < 方片 10 > → 10 分
    < 梅花 Ⅰ > → 11 分
    < 红桃 Ⅱ > → 12 分
    < 黑桃 Ⅲ > → 13 分
    < 方片 O > → 14 分

    
    
    
    ]]

local gameInfo = {
    "游戏名称：卡牌游戏",
    "作者：赵子睿",
    "版权所有 © 2025 保留所有权利"
}

local fontText = 24
local fontGameInfo = 16
local wrappedTextLines = {}
local scrollY = 0
local lineHeight
local isDragging = false
local dragStartY = 0
local dragStartScrollY = 0

-- 下方提示信息
local fontBottom = 18
local flipBottom = true
local timer = 0
local duration = 2.4
local active = true

local paper = {
    image = love.graphics.newImage("assets/paper.jpg"),
    scaleX = 0,
    scaleY = 0,
}

-- 文本处理函数：仅处理手动换行和段落，不做自动换行
local function wrapText(linesArray)
    if not linesArray then return {} end

    local wrappedLines = {}

    for _, eachLine in ipairs(linesArray) do
        -- 处理段落分隔：空行视为段落分隔（添加空行表示分段）
        if eachLine == "" then
            -- 避免连续添加多个空行（连续空行只保留一个作为段落分隔）
            if #wrappedLines == 0 or wrappedLines[#wrappedLines] ~= "" then
                table.insert(wrappedLines, "")
            end
        else
            -- 直接保留原始行（含缩进），不做任何自动换行
            table.insert(wrappedLines, eachLine)
        end
    end

    return wrappedLines
end

local function init()
    -- 将长字符串按换行符分割为行数组（核心：手动换行由输入的换行符决定）
    local originalTextLines = {}
    for eachLine in longText:gmatch("([^\n]*)\n?") do  -- 按换行符\n分割
        table.insert(originalTextLines, eachLine)
    end

    fontHandler.setFont(fontText)
    lineHeight = fontHandler.getFontHeight()
    wrappedTextLines = wrapText(originalTextLines)  -- 不再传递maxWidth（无需自动换行）

    paper.scaleX = width / paper.image:getWidth()
    paper.scaleY = height / paper.image:getHeight()
end

local function update(dt)
    -- 限制滚动范围
    local maxScrollY = math.max(0, #wrappedTextLines * lineHeight - height + padding * 2)
    scrollY = math.max(0, math.min(maxScrollY, scrollY))

    if active then
        timer = timer + dt
        if timer >= duration then
            timer = timer - duration
            flipBottom = not flipBottom
        end
    end
end

-- 绘制虚线的辅助函数（兼容旧版LÖVE）
local function drawDashedLine(x1, y1, x2, y2, dashLength, gapLength)
    dashLength = dashLength or 5
    gapLength = gapLength or 3

    local dx = x2 - x1
    local dy = y2 - y1
    local length = math.sqrt(dx * dx + dy * dy)

    if length == 0 then return end

    local unitX = dx / length
    local unitY = dy / length

    local currentX, currentY = x1, y1
    local segmentLength = dashLength + gapLength
    local totalSegments = math.ceil(length / segmentLength)

    for i = 0, totalSegments - 1 do
        local dashStartX = currentX + unitX * i * segmentLength
        local dashStartY = currentY + unitY * i * segmentLength
        local dashEndX = dashStartX + unitX * dashLength
        local dashEndY = dashStartY + unitY * dashLength

        -- 确保线段不超出总长度
        if (dashEndX - x1) * unitX + (dashEndY - y1) * unitY > length then
            dashEndX = x1 + unitX * length
            dashEndY = y1 + unitY * length
        end

        line(dashStartX, dashStartY, dashEndX, dashEndY)
    end
end

local function draw()
    setColor(1, 1, 1)
    drawg(paper.image, 0, 0, 0, paper.scaleX, paper.scaleY)

    -- 绘制文本（完全按手动换行显示）
    fontHandler.setFont(fontText)
    setColor(0, 0, 0)
    for i, eachLine in ipairs(wrappedTextLines) do
        local y = (i - 1) * lineHeight - scrollY + padding
        -- 仅当行在显示范围内时才绘制（优化性能）
        if y + lineHeight > 0 and y < height then
            printg(eachLine, padding, y)
        end
    end

    -- 绘制滚动条背景
    setColor(0.8, 0.8, 0.8, 0.5)
    local scrollbarWidth = padding
    local scrollbarX = width - scrollbarWidth - padding / 5
    local scrollbarHeight = height - padding * 2
    drawRectangle("fill", scrollbarX, padding, scrollbarWidth, scrollbarHeight, 3)

    -- 计算并绘制滚动条滑块
    local maxScrollY = math.max(0, #wrappedTextLines * lineHeight - height + padding * 2)
    if maxScrollY > 0 then
        local sliderHeight = math.max(padding * 2, scrollbarHeight * (scrollbarHeight / (#wrappedTextLines * lineHeight)))
        local sliderY = padding + (scrollY / maxScrollY) * (scrollbarHeight - sliderHeight)

        setColor(0.4, 0.4, 0.4)
        drawRectangle("fill", scrollbarX, sliderY, scrollbarWidth, sliderHeight, 3)
    end

    -- 绘制操作提示
    if active then
        fontHandler.setFont(fontBottom)
        setColor(0, 0, 0, 0.7)
        drawRectangle("fill", 0, height - lineHeight - padding, width, lineHeight)
        setColor(1, 1, 1, 0.7)
        if flipBottom then
            printf("使用鼠标拖拽、滚轮或上下方向键滚动", 0, height - lineHeight, width, "center")
        else
            printf("鼠标右键返回", 0, height - lineHeight, width, "center")
        end
    end

    -- 绘制游戏信息
    if scrollY >= maxScrollY - lineHeight - padding then  -- 滚动到底部时显示
        -- 绘制虚线分隔线
        setColor(0, 0, 0, 0.3)
        setLineWidth(1)

        local dashY = height - (#gameInfo + 1) * lineHeight - lineHeight
        drawDashedLine(padding * 3, dashY, width - padding * 3, dashY, 5, 3)

        -- 绘制游戏信息
        fontHandler.setFont(fontGameInfo)
        for i, eachLine in ipairs(gameInfo) do  
            local y = height - (#gameInfo - i + 1) * lineHeight - lineHeight
            printf(eachLine, 0, y, width, "center")
        end
    end
end

-- 鼠标和键盘事件处理函数
local function mousepressed(x, y)
    -- 检查是否点击了滚动条
    local scrollbarWidth = 10
    local scrollbarX = width - scrollbarWidth - 5
    local scrollbarHeight = height - 20

    if x >= scrollbarX and x <= scrollbarX + scrollbarWidth and y >= 10 and y <= 10 + scrollbarHeight then
        isDragging = true
        local maxScrollY = math.max(0, #wrappedTextLines * lineHeight - height + padding * 2)
        if maxScrollY > 0 then
            local sliderHeight = math.max(20, scrollbarHeight * (scrollbarHeight / (#wrappedTextLines * lineHeight)))
            local sliderY = padding + (scrollY / maxScrollY) * (scrollbarHeight - sliderHeight)

            if y >= sliderY and y <= sliderY + sliderHeight then
                dragStartY = y
                dragStartScrollY = scrollY
            else
                -- 点击滚动条空白处跳转
                local targetPos = (y - 10 - sliderHeight/2) / (scrollbarHeight - sliderHeight)
                scrollY = targetPos * maxScrollY
            end
        end
    else
        -- 点击文本区域拖拽滚动
        isDragging = true
        dragStartY = y
        dragStartScrollY = scrollY
    end
end

local function mousereleased()
    isDragging = false
end

local function mousemoved(y)
    if isDragging then
        scrollY = dragStartScrollY - (y - dragStartY)
    end
end

local function wheelmoved(y)
    scrollY = scrollY - y * 30
end

local function keypressed(key)
    if key == "up" then
        scrollY = scrollY - 30
    elseif key == "down" then
        scrollY = scrollY + 30
    end
end

return{
    init = init,
    update = update,
    draw = draw,
    deactive = function() active = false end,
    mousepressed = mousepressed,
    mousereleased = mousereleased,
    mousemoved = mousemoved,
    wheelmoved = wheelmoved,
    keypressed = keypressed
}